package controllers

import (
	"encoding/json"
	"errors"
	"qysoft/models"
	//	"strconv"
	"qysoft/libs/encrypt"
	//	"reflect"
	// "strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

//RoleController oprations for Role
type RoleController struct {
	CommonController
}

// URLMapping 方法映射
func (c *RoleController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetRoleList", c.GetRoleList)
	c.Mapping("DeleteRoles", c.DeleteRoles)
	c.Mapping("GetRoleResourceTree", c.GetRoleResourceTree)
	c.Mapping("GetOrgRoleList", c.GetOrgRoleList)
	c.Mapping("AssignResources", c.AssignResources)
	c.Mapping("GetResByRole", c.GetResByRole)

}

// Post create Role
// @Title Post
// @Description create Role
// @Param	body		body 	models.Role	true		"body for Role content"
// @Success 201 {int} models.Role
// @Failure 403 body is empty
// @router / [post]
func (c *RoleController) Post() {
	var v models.Role
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &v)
	// sdata, _ := rdata.(map[string]interface{})
	// v.Name, _ = sdata["Name"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime

	// vtype, _ := sdata["Type"].(string)
	// v.Type, _ = strconv.Atoi(vtype)
	v.Id = encrypt.GetGuid()
	_, err = models.AddRole(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)

	}
	c.Dlog("添加了角色", v.Id)
	rt := make(map[string]interface{})
	rt["Id"] = v.Id
	c.RetSuccess(rt)

}

// GetOne get Role by id
// @Title Get
// @Description get Role by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Role
// @Failure 403 :id is empty
// @router /:id [get]
func (c *RoleController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetRoleById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetAll  get All Role
// @Title Get All
// @Description get Role
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Role
// @Failure 403
// @router / [get]
func (c *RoleController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]string)
	var limit int64 = -1
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllRole(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// Update update the Role
// @Title Update
// @Description update the Role
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Role	true		"body for Role content"
// @Success 200 {object} models.Role
// @Failure 403 :id is not int
// @router /Update [post]
func (c *RoleController) Update() {
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var u models.Role
	err = json.Unmarshal(rdata, &u)
	v, err := models.GetRoleById(u.Id)
	if err != nil {
		c.RetError(ErrInputData)
	}
	// v = &u
	// v.Name, _ = sdata["Name"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	u.Updater = user.Name
	u.Utime = time.Now()
	// vtype, _ := sdata["Type"].(string)
	// v.Type, _ = strconv.Atoi(vtype)
	err = models.UpdateRoleById(&u)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("修改了角色", u.Id, 1, v)
	c.RetSuccess(u.Id)

}

// Delete delete the Role
// @Title Delete
// @Description delete the Role
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *RoleController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError(ErrInputData)
	}
	if err := models.SoftDeleteRole(id, user.Name); err == nil {
		c.Dlog("删除了角色", id)
		rt := make(map[string]interface{})
		rt["Id"] = id
		c.RetSuccess(rt)
	}
	c.RetError(ErrDatabase)
}

// GetRoleList 获取有效角色列表
// @Title GetRoleList
// @Description 获取有效角色列表
// @Success 200 {string} get success!
// @Failure 403 id is empty
// @router /GetRoleList [get]
func (c *RoleController) GetRoleList() {
	var fields []string
	var sortby []string
	var order []string
	var limit int64 = -1
	var offset int64
	query := make(map[string]string)
	query["status"] = "1"
	fields = append(fields, "Id", "Name")

	l, err := models.GetAllRole(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// GetOrgRoleList 单位管理员获取有效角色列表，排除系统管理员
// @Title GetOrgRoleList
// @Description 单位管理员获取有效角色列表，排除系统管理员
// @Success 200 {string} get success!
// @Failure 403 id is empty
// @router /GetOrgRoleList [get]
func (c *RoleController) GetOrgRoleList() {
	//	user, _ := c.GetUserinfo()
	//	rdata, err := c.AesDecode(c.GetString("tdata"))
	//	if err != nil {
	//		c.RetError(ErrToken)
	//	}
	//	sdata, _ := rdata.(map[string]interface{})
	user := c.User
	beego.Error("err is :")
	l, err := models.GetOrgRoleList(user)
	beego.Error("err is :", err)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// DeleteRoles 删除角色列表
// @Title DeleteRoles
// @Description DeleteRoles
// @Success 200  success!
// @Failure 403
// @router /DeleteRoles [post]
func (c *RoleController) DeleteRoles() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteRole(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了角色", id)
	}

	c.RetSuccess("ok")
}

// AssignResources 角色分配资源
// @Title 角色分配资源
// @Description 角色分配资源
// @Success 200 GrantResources success!
// @Failure 403
// @router /AssignResources [post]
func (c *RoleController) AssignResources() {
	//	user, _ := c.GetUserinfo()
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	roleid, _ := sdata["Roleid"].(string)
	//	roleid := int64(sid)
	resources, _ := sdata["Resources"].([]interface{})
	if err := models.DeleteRoleResourceByRoleId(roleid); err != nil {
		c.RetError(ErrDatabase)
	}
	// pr := make([]string, 0)
	er := make([]string, 0)
	for _, r := range resources {
		// strid, _ := r.(map[string]interface{})
		// id := strid["id"].(string)
		id := r.(string)
		//		if !ok {
		//			c.RetError(ErrInputData)
		//		}
		//		id := int64(resid)
		er = append(er, id)
		// val, err := models.GetResourceById(id)
		// if err == nil && val.Pid != "0" {
		// 	pr = append(pr, val.Pid)
		// }
	}
	//	子资源非完全授权后需对父资源授权
	// for _, v := range pr {
	// 	isv := false
	// 	for _, e := range er {
	// 		if e == v {
	// 			isv = true
	// 			break
	// 		}
	// 	}
	// 	if !isv {
	// 		er = append(er, v)
	// 	}
	// }
	for _, res := range er {
		beego.Debug(roleid, res)
		if _, err := models.AddRoleResource(roleid, res); err != nil {
			beego.Error(err)
			c.RetError(ErrDatabase)
		}
	}
	c.RetSuccess("ok")
}

// GetRoleResourceTree  获取角色资源树通过角色id
// @Title 获取角色资源树
// @Description get 获取角色资源树通过角色id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.RoleResource
// @Failure 403 :id is empty
// @router /GetRoleResourceTree/:id [get]
func (c *RoleController) GetRoleResourceTree() {
	id := c.GetString(":id")
	//	id, err := strconv.ParseInt(idStr, 10, 64)
	//	if err != nil {
	//		c.RetError(ErrInputData)
	//	}
	// models.AddResOpe()
	tree := models.GetResTreeByRoleId(id)
	c.RetSuccess(tree)
}

// GetResByRole  获取角色资源树通过角色id
// @Title 获取角色资源树
// @Description get 获取角色资源树通过角色id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.RoleResource
// @Failure 403 :id is empty
// @router /GetResByRole/:id [get]
func (c *RoleController) GetResByRole() {
	id := c.GetString(":id")
	//	id, err := strconv.ParseInt(idStr, 10, 64)
	//	if err != nil {
	//		c.RetError(ErrInputData)
	//	}
	// models.AddResOpe()
	tree := models.GetAllResByRoleId(id)
	// beego.Debug(tree)
	c.RetSuccess(tree)
}
